package org.example.videotran.controller;

import org.example.videotran.exception.AppException;
import org.example.videotran.exception.AppExceptionCodeMsg;
import org.example.videotran.pojo.ResponseMessage;
import org.example.videotran.pojo.User;
import org.example.videotran.pojo.dto.UserDto;
import org.example.videotran.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController //接口方法返回对象转换为json文本
@RequestMapping("/user") //localhost:8080/user/***
public class UserController {

    @Autowired
    IUserService iUserService;

    @PostMapping("/loginByPhone")
    public ResponseMessage<User> loginByPhone(@RequestBody UserDto userDto){
        String token = iUserService.loginByPhone(userDto);
        if (token != null) {
            return ResponseMessage.success(token);
        }else {
            throw new AppException(AppExceptionCodeMsg.INCORRECT_PHONE_PASSWORD);
        }
    }

    @PostMapping("/loginByEmail")
    public ResponseMessage<User> loginByEmail(@RequestBody UserDto userDto){
        String token = iUserService.loginByEmail(userDto);
        if (token != null) {
            return ResponseMessage.success(token);
        }else {
            throw new AppException(AppExceptionCodeMsg.INCORRECT_PHONE_PASSWORD);
        }
    }

    @PostMapping("/register")
    public ResponseMessage<User> register(@RequestBody UserDto userDto){
        if(iUserService.register(userDto)){
            return ResponseMessage.success();
        }else {
            return ResponseMessage.fail("该用户已注册");
        }
    }

    @GetMapping("/getUser")
    public ResponseMessage<User> getUser( @RequestHeader(name = "token", required = false) String token ){
        User user = iUserService.getUser(token);
        if (user != null) {
            return ResponseMessage.success(user);
        }else {
            return ResponseMessage.fail("没有该用户");
        }
    }

}
